package pl.edu.agh.agents.gui.actions;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import pl.edu.agh.agents.gui.GUI;
import pl.edu.agh.agents.gui.GraphFileFilter;
import pl.edu.agh.agents.gui.GraphSaver;
import pl.edu.agh.agents.state.State;

import com.mxgraph.model.mxCell;

// dumps current configuration to file
public class SaveAction extends AbstractAction {
	private static final long serialVersionUID = -1940878883959876753L;
	private GUI gui;

	public SaveAction(String name, GUI gui) {
		super(name);

		this.gui = gui;
	}

	private String chooseFile() {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(gui.getDir());

		FileFilter filter = new GraphFileFilter();
		chooser.setFileFilter(filter);
		chooser.setApproveButtonText("Save");
		chooser.setDialogTitle("Save");

		int returnVal = chooser.showOpenDialog(gui.getGraphComponent());
		if (returnVal != JFileChooser.APPROVE_OPTION) {
			return null;
		}

		String filename = chooser.getSelectedFile().getAbsolutePath();
		if (!filename.endsWith(".graph")) {
			filename = filename + ".graph";
		}

		System.out.println("You chose to save to this file: " + filename);
		gui.setDir(chooser.getCurrentDirectory());
		
		return filename;
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		String filename = chooseFile();
		if (filename == null) {
			return;
		}

		List<Point> points = new ArrayList<Point>();
		
		for (State state : gui.getStates()) {
			mxCell cell = gui.getCellForState(state);
			int x = (int)cell.getGeometry().getX();
			int y = (int)cell.getGeometry().getY();
			points.add(new Point(x, y));
		}
		
		GraphSaver saver = GraphSaver.getInstance();
		saver.saveGraphToFile(filename, gui.getStates(), points, gui.getAgents(), gui.getAgentColors());
		
		gui.setGraphPath(filename);
	}
}